import { createRouter, createWebHashHistory } from 'vue-router'
import Home from '../components/Home.vue'
import Login  from '../components/Login.vue'
const routes = createRouter({
    history: createWebHashHistory(),
    routes: [
        {
            path: '/',
            component: Home
        },
        {
            path: '/login',
            component: Login
        },
        {
            path: '/home',
            component: Home
        }
    ]
})

routes.beforeEach((to, from, next) => {
  // 如果是登录页，直接放行
  if (to.path === '/login') {
    next();
    return; // 防止继续执行下面的逻辑
  }
  
  // 判断该路由是否需要登录权限
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 检查是否已登录
    const username = window.sessionStorage.getItem('username')
    if (username != null) {
      next()
    } else {
      // 未登录，跳转到登录页
      next('/login')
    }
  } else {
    next()
  }
})

export default routes